<template>
  <!-- 重量段配置 -->
  <el-dialog :title="$t('label_pms_weight_range_cfg')" :visible.sync="weightRangeDialogFormVisible" width="1200px">
    <ex_header_spiler title="区间配置"></ex_header_spiler>
    <el-form inline>
      <!-- 生成方式 -->
      <el-form-item :label="$t('label_pms_generate_type')" labelWidth="90px">
        <el-radio-group v-model="weightForm.genType">
          <!-- 按步长 -->
          <el-radio-button label="byStep">{{ $t('label_pms_by_step') }}</el-radio-button>
          <!-- 按分段数量 -->
          <el-radio-button label="byNumber">{{ $t('label_pms_by_split_num') }}</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <!-- 最大体积 CBM': '最大重量 Kg -->
      <el-form-item :label="$t('label_pms_max_weight') + 'KG'">
        <el-input-number v-model="weightForm.maxWeight" style="width: 140px;" :min="1" :max="100000"></el-input-number>
      </el-form-item>
      <!-- 分段数量 -->
      <el-form-item :label="$t('label_pms_split_nums')" v-if="weightForm.genType == 'byNumber'">
        <el-input-number v-model="weightForm.number" style="width: 140px;" :min="1" :max="100"></el-input-number>
      </el-form-item>
      <!-- 步长体积 CBM': '步长重量 KG -->
      <el-form-item :label="$t('label_pms_stop_weight') + ' KG'" v-if="weightForm.genType == 'byStep'">
        <el-input v-model="weightForm.step" style="width: 100px;"></el-input>
      </el-form-item>

      <!-- 生成 -->
      <el-button @click="generateWeights">{{ $t('label_pms_gernate') }}</el-button>

      <!-- 确认  -->
      <el-button @click="confirmRange">确认</el-button>

      <br />
      <!-- 体积段配置   重量段配置 -->
      <el-form-item :label="$t('label_pms_weight_range_cfg')" labelWidth="90px">
        <div style="width: 810px; display: flex; display: flex; flex-direction: row; flex-wrap: wrap;">
          <div v-for="(item, index) in weightArray" :key="index" class="weightRangeWrap"
            @mouseover="item.showRemove = true" @mouseleave="item.showRemove = false">
            <i v-show="item.showRemove" @click="weightArrayAdd(index)" class="el-icon-circle-plus"
              style="position: absolute; top: 0px; left: 0px; cursor: pointer; color: #67C23A;z-index: 10;"></i>
            <el-input type="number" v-model.number="item.value" class="weightRangeInput" />
            <i v-if="index > 0 && index < weightArray.length - 1" v-show="item.showRemove"
              @click="weightArray.splice(index, 1)" class="el-icon-remove"
              style="position: absolute; top: 0px; right: 0px; cursor: pointer; color: #d74343; z-index: 10;"></i>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <ex_header_spiler title="价格配置"></ex_header_spiler>
    <el-form label-width="80px" class="common-form-panel-div" style="padding-left: 10px;">
      <el-form-item label="计价模式">
        <el-radio-group v-model="weightRangeFrom.priceType" style="padding-left: 10px;">
          <!-- 单价 -->
          <el-radio label="SINGLE">
            {{ $t('PmsTransportPriceTypeEnum__SINGLE') }}
          </el-radio>
          <!-- 续重-->
          <el-radio label="ADD">
            {{ $t('PmsTransportPriceTypeEnum__ADD') }}
          </el-radio>
          <!-- 总价 -->
          <el-radio label="TOTAL">
            {{ $t('PmsTransportPriceTypeEnum__TOTAL') }}
          </el-radio>
          <!-- 首重+续重 -->
          <el-radio label="MULTI_ADD">
            {{ $t('PmsTransportPriceTypeEnum__MULTI_ADD') }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="价格配置">
        <div class="flex_row" style="overflow: auto">
          <div v-for="(item, index) in weightRangeFrom.priceRanges" style="min-width: 150px;" class="flexuse">
            <div>
              <div class="flex_center">{{ getElLabel(item, index) }}</div>
              <div v-if="weightRangeFrom.priceType === 'MULTI_ADD'"
                style="display: flex; padding: 0px 8px; justify-content: space-around; ">
                <div style="text-align: center;">首重价</div>
                <div style="text-align: center;">续重价</div>
              </div>
            </div>
            <template v-if="weightRangeFrom.priceType !== 'MULTI_ADD'">
              <el-input type="text" v-model="item.price" class="price-edit-inner-input" style="width: 80%;" />
            </template>
            <template v-else-if="weightRangeFrom.priceType === 'MULTI_ADD'">
              <div style="display: flex; padding: 4px 8px; justify-content: space-between;">
                <el-input type="text" v-model="weightRangeFrom.priceRanges[index].startPrice"
                  class="price-edit-inner-input" style="width: 44%;" />
                <el-input type="text" v-model="weightRangeFrom.priceRanges[index].addPrice"
                  class="price-edit-inner-input" style="width: 44%;" />&nbsp;
              </div>

            </template>
          </div>
        </div>
      </el-form-item>
      <span style="color: #666; line-height: 32px; margin-top: 10px;height: 40px; ">
        <i class="el-icon-warning" style="margin-right: 6px;"></i>区间命中规则： 起始 <= 匹配值 < 终止</span>
    </el-form>

    <div slot="footer" class="dialog-footer" style=" margin-left: 150px; ">
      <div>
        <el-button @click="weightRangeDialogFormVisible = false">{{ $t('label_cancel') }}</el-button>
        <el-button type="primary" @click="saveWeightRange">{{ $t('label_save') }}</el-button>
      </div>
    </div>

  </el-dialog>
</template>
    <!--  -->
    <script>
    export default {
      data() {
        return {
          weightRangeDialogFormVisible: false,
          "weightForm": {
            "genType": "byNumber",
            "maxWeight": 100,
            "number": 20,
            "step": 0.5
          },

          "weightArray": [{
            "showRemove": false,
            "value": 0
          }, {
            "showRemove": false,
            "value": 30
          }, {
            "showRemove": false,
            "value": 90
          }, {
            "showRemove": false,
            "value": 180
          }, {
            "showRemove": false,
            "value": 360
          }],

          "editWeightTableRows": [],
          weightRangeFrom: {},
          updateWeightRangeKey: '',
          weightUnit: 'kg'
        }
      },
      methods: {
        show(row, index, key, weightUnit) {
          this.weightUnit = weightUnit
          this.weightRangeFrom = JSON.parse(JSON.stringify(row));
          this.weightRangeFrom.index = index;
          this.weightRangeFrom.key = key;
          if (_.isEmpty(this.weightRangeFrom.priceRanges)) {
            this.weightRangeFrom.priceRanges = []
          }
          if (_.isEmpty(this.weightRangeFrom.priceType)) {
            this.$set(this.weightRangeFrom, 'priceType', 'SINGLE');
          }

          this.weightRangeDialogFormVisible = true
        },

        generateWeights() {

          let weightForm = this.weightForm
          let step = parseFloat(weightForm.step)

          if (weightForm.genType == 'byNumber') {
            step = (parseFloat(weightForm.maxWeight) / parseFloat(weightForm.number))
          }
          let max = parseInt(weightForm.maxWeight)
          let arr = []
          let start = 0
          while (true) {
            if (start >= max) {
              arr.push({
                "showRemove": false,
                "value": max
              })
              break
            }
            arr.push({
              "showRemove": false,
              "value": start
            })
            start += step
            start = parseFloat(start.toFixed(3))
          }
          this.weightArray = arr
        },
        confirmRange() {

          let editWeightTableHead = []

          let samplePricePeriod = []

          if (this.weightRangeFrom.priceType === 'MULTI_ADD' && this.weightArray.length <= 2) {
            this.$message({
              type: 'error',
              message: '首重+续重计价模式分段数量必须大于1'
            })
            return
          }
          this.weightArray = this.weightArray.filter(_ => _.value || _.value === 0)
          for (let i = 0; i < this.weightArray.length; i++) {

            let e = this.weightArray[i].value

            let isNum = this.$isNumber(e)

            if (!isNum) {
              this.$message({
                'type': 'error',
                'message': e + ' is not a number'
              })

              return
            }

            if (i == 0) {
              continue;
            }

            if (parseFloat(this.weightArray[i].value) <= parseFloat(this.weightArray[i - 1].value)) {
              this.$message({
                'type': 'error',
                'message': '数据必须从小到大排列'
              })
              return
            }

            editWeightTableHead.push({
              id: 'id_' + Math.random(),
              value: this.weightArray[i - 1].value + '-' + this.weightArray[i].value
            })

            samplePricePeriod.push({
              "start": this.weightArray[i - 1].value,
              "end": this.weightArray[i].value,
              "price": 10,
              "startPrice": 10,
              "addPrice": 10,
              "unit": this.weightUnit
            })
          }

          this.samplePricePeriod = samplePricePeriod

          // 首重值
          // this.firstWeightValue = this.weightArray[1].value

          this.editWeightTableHead = editWeightTableHead

          let tmp = [].concat(JSON.parse(JSON.stringify(samplePricePeriod)))
          this.weightRangeFrom.priceRanges = tmp
          this.$set(this, 'weightRangeFrom', _.clone(this.weightRangeFrom));
        },
        getElLabel(item, index) {

          item.value = item.start + '-' + item.end

          let unit = this.weightUnit

          // 续重 - 首重价
          if (index == 0 && this.weightRangeFrom.priceType == 'ADD') {
            let tmps = item.value.split('-')
            return `${tmps[1]}${unit} ` + this.$t('label_pms_under_price')
          }
          // 总价
          else if (this.weightRangeFrom.priceType == 'TOTAL') {
            return `${item.value}${unit} ` + this.$t('label_pms_total_price')
          }
          // 续重 - 续重价
          else if (this.weightRangeFrom.priceType == 'ADD') {
            return `${item.value}${unit} ` + this.$t('label_pms_added_price')
          }
          // 首重 + 续重
          else if (this.weightRangeFrom.priceType == 'MULTI_ADD') {
            return `${item.value}${unit}`
          } else if (this.weightRangeFrom.priceType == 'SINGLE') {
            return `${item.value}${unit}`
          }

          return item.value
        },
        saveWeightRange() {
          // 校验数据
          if (this.weightRangeFrom && this.weightRangeFrom.priceRanges.length > 0) {
            for (let i = 0; i < this.weightRangeFrom.priceRanges.length; i++) {

              var e = this.weightRangeFrom.priceRanges[i];

              let price = e.price
              if (!this.$isNumber(price)) {
                this.$message({
                  'type': 'error',
                  'message': price + ' is not a number'
                })
                return
              }

              let start = e.start
              if (!this.$isNumber(start)) {
                this.$message({
                  'type': 'error',
                  'message': 'start' + ' is not a number or null'
                })
                return
              }

              let end = e.end
              if (!this.$isNumber(end)) {
                this.$message({
                  'type': 'error',
                  'message': 'end' + ' is not a number or null'
                })
                return
              }

              if (i == 0) {
                continue
              }

              if (parseFloat(this.weightRangeFrom.priceRanges[i].start) < parseFloat(this.weightRangeFrom.priceRanges[i - 1].end) ||
                parseFloat(this.weightRangeFrom.priceRanges[i].start) != parseFloat(this.weightRangeFrom.priceRanges[i - 1].end)) {
                this.$message({
                  'type': 'error',
                  'message': '区间段数据必须连续，且必须从小到大排列，前一个区间结束值必须等于下一个区间起始值'
                })
                return
              }

            }
          }

          this.weightRangeDialogFormVisible = false
          this.$emit('getWeightRangeFromData', this.weightRangeFrom)
        },
        weightArrayAdd(index) {
          let value = (this.weightArray[index].value + (index > 0 ? this.weightArray[index - 1].value : 0)) / 2
          this.weightArray.splice(index, 0, { showRemove: true, value: Number(value.toFixed(3)) })
          this.weightArray[index + 1].showRemove = false
        },
      },
    }
</script>
    <style scoped lang='scss'>
    .weightRangeWrap {
      padding: 0px 6px 0px 6px;
      position: relative;

      .weightRangeInput {
        width: 40px;
        font-size: 14px;
        text-align: center;

        >>>.el-input__inner {
          border: none !important;
          padding: 0 !important;
          text-align: center;
        }
      }
    }
  </style>
